package com.aoyama.juc.volatiles;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author ：qs
 * @date ：Created in 2022/6/5
 * @description： 功能描述: ABA问题的解决
 * @modified By：
 */
public class Video19_02 {
    /*
    注意与 Video19_01中的 AtomicReference 有区别，它自己维护了一个类似时间戳的数值
     */
    static AtomicStampedReference<Integer> num = new AtomicStampedReference<>(100,1);

    public static void main(String[] args) {
        int stamp = num.getStamp();//初始版本号

        new Thread(() ->{
            num.compareAndSet(100,101,num.getStamp(),num.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "\t 版本号" + num.getStamp());
            num.compareAndSet(101,100,num.getStamp(),num.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "\t 版本号" + num.getStamp());
        },"线程A").start();


        new Thread(() ->{
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = num.compareAndSet(100, 209, stamp, num.getStamp() + 1);
            System.out.println(b + "\t 当前版本号: \t" + num.getStamp());
            System.out.println("当前最新值 \t" + num.getReference().toString());
        },"线程B").start();
    }
}
